package LC;

/**
 * https://leetcode.com/problems/remove-linked-list-elements/description/
 * Remove all elements from a linked list of integers that have value val.
 * Example
 * Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
 * Return: 1 --> 2 --> 3 --> 4 --> 5
 * Credits:
 * Special thanks to @mithmatt for adding this problem and creating all test cases.
 */
public class LC_203_RemoveLinkedListElements_LinkedList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        int val = 2;

        ListNode h1 = Solution.removeElements(head, val);
        ListNode cur = h1;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    static class Solution {
        static ListNode removeElements(ListNode head, int val) {
            if (head == null)
                return null;
            ListNode correct = new ListNode(0);
            correct.next = head;
            ListNode pre = correct;
            ListNode cur = correct.next;
            while (cur.next != null) {
                if (cur.val == val) {
                    pre.next = cur.next;
                } else {
                    pre = pre.next;
                }
                cur = cur.next;
            }
            if (cur.val == val)
                pre.next = null;
            return correct.next;
        }
    }
}